<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" formType="add" :cols="2" labelWidth="120" :isSubmitBtn="false" @formChange="formChange" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton type="primary" :click="saveAddform">保 存</AjaxButton>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getDiscountmodesDetail, addDiscountmodes, updataDiscountmodes, getDiscountModeCod } from '@/api/repair/repairBusiness/preferentialWay';
import { checkDate } from '@/utils/validate';
import { findFormItem } from '@/utils';
export default {
  name: 'PreferentialWayAddFrom',
  mixins: [dictionary],
  data() {
    return {
      formList: this.createFormList(),
      saveData: null,
      status: 'add',
      dataId: null,
      timeLimited: null
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  watch: {
    timeLimited() {
      console.log(this.timeLimited, 'timeLimited');
      if (this.timeLimited == 10041001) {
        this.formList.find(item => item.fieldName === 'discountBeginTime|discountEndTime').disabled = false;
        this.formList.find(item => item.fieldName === 'discountBeginTime|discountEndTime').rules = [{ required: true, message: '请选择优惠时段', trigger: 'blur' }];
        this.formList = [...this.formList];
      } else if (this.timeLimited == 10041002) {
        this.formList.find(item => item.fieldName === 'discountBeginTime|discountEndTime').disabled = true;
        this.formList.find(item => item.fieldName === 'discountBeginTime|discountEndTime').initialValue = [];
        this.formList.find(item => item.fieldName === 'discountBeginTime|discountEndTime').rules = [];
        this.formList = [...this.formList];
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.status === 'edit') {
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '优惠模式代码',
          fieldName: 'discountModeCode',
          disabled: true,
          // maxlength: 4,
          rules: [
            { required: true, message: '请输入优惠模式代码', trigger: 'blur' }
            // { pattern: /^(\w){1,4}$/, message: '请输入正确的优惠模式代码' }
          ]
          // change: val => {
          //   this.changeNameSelect(val);
          // }
        },
        {
          type: 'INPUT',
          label: '优惠模式名称',
          maxlength: 20,
          fieldName: 'discountModeName',
          rules: [{ required: true, message: '请输入优惠模式名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '工时费优惠率',
          max: 1,
          precious: 2,
          fieldName: 'labourAmountDiscount',
          isControls: false,
          rules: [{ required: true, message: '请输入正确优惠率', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '维修材料费优惠率',
          max: 1,
          precious: 2,
          fieldName: 'repairPartDiscount',
          isControls: false,
          rules: [{ required: true, message: '请输入正确优惠率', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '销售材料费优惠率',
          max: 1,
          precious: 2,
          fieldName: 'salesPartDiscount',
          isControls: false,
          rules: [{ required: true, message: '请输入正确优惠率', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '附加费优惠率',
          max: 1,
          precious: 2,
          fieldName: 'additionalItemsDiscount',
          isControls: false,
          rules: [{ required: true, message: '请输入正确优惠率', trigger: 'blur' }]
        },
        // {
        //   type: 'SELECT',
        //   itemList: this.createDictList('1004'),
        //   label: '保险类默认无优惠',
        //   fieldName: 'noDiscountByInsurance',
        //   placeholder: '请选择...',
        //   initialValue: 10041002,
        //   rules: [{ required: true, message: '请选择保险类默认无优惠', trigger: 'blur' }]
        // },
        {
          type: 'SELECT',
          itemList: this.createDictList('1001'),
          label: '状态',
          fieldName: 'isValid',
          placeholder: '请选择...',
          rules: [{ required: true, message: '请选择状态', trigger: 'blur' }],
          initialValue: 10011001
        },
        {
          type: 'DATE',
          label: '开始日期',
          fieldName: 'discountBeginDate',
          placeholder: '请选择...',
          rules: [{ required: true, message: '请选择开始日期', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '结束日期',
          fieldName: 'discountEndDate',
          placeholder: '请选择...',
          rules: [
            { required: true, message: '请选择结束日期', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                // 获取起始时间
                const start = this.formList.find(x => x && x.fieldName == 'discountBeginDate').initialValue;
                if (value < start) {
                  callback(new Error('请检查时间范围'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ]
        }
        // {
        //   type: 'SELECT',
        //   itemList: this.createDictList('1004'),
        //   label: '启用优惠时段',
        //   fieldName: 'isTimeLimited',
        //   placeholder: '请选择...',
        //   initialValue: 10041002,
        //   change: props => {
        //     this.isTimeLimited(props);
        //   },
        //   rules: [{ required: true, message: '请选择启用优惠时段', trigger: 'blur' }]
        // },
        // {
        //   type: 'RANGE_TIME',
        //   label: '优惠时段',
        //   fieldName: 'discountBeginTime|discountEndTime',
        //   placeholder: '请选择...',
        //   disabled: true
        // }
      ];
    },
    // 校验数字，保留两位
    checkNumber(rule, value, callback) {
      let start = String(value).indexOf('.');
      if (start != -1) {
        if (String(value).split('.')[1].length > 2) {
          callback(new Error('小数点后保留数字不可超两位'));
        }
        callback();
      }
    },
    openModel(status, row) {
      this.status = status;
      if (status == 'add') this.initDefaultDiscountModeCode();
      if (row) {
        this.dataId = row.discountModeId;
        this.formList.find(item => item.fieldName === 'discountModeCode').disabled = true;
        this.getDiscountmodesDetail(this.dataId);
      }
    },
    // 新建优惠模式自动生成优惠模式代码
    async initDefaultDiscountModeCode() {
      let res = await getDiscountModeCod();
      if (res.resultCode == 200) {
        findFormItem(this.formList, 'discountModeCode').initialValue = res.data;
      }
    },
    async getDiscountmodesDetail(code) {
      const res = await getDiscountmodesDetail(code);
      let beginTime;
      let endTime;
      // console.log("res",res)
      for (let [key, value] of Object.entries(res.data.rows[0])) {
        // console.log(key)
        this.formList.some(item => {
          if (item.fieldName === key) {
            item.initialValue = value;
            return true;
          }
        });
        if (key === 'discountBeginTime') {
          beginTime = value;
        }
        if (key === 'discountEndTime') {
          endTime = value;
        }
      }
      // console.log(beginTime,endTime);
      let rangeTime = [];
      rangeTime.push(beginTime);
      rangeTime.push(endTime);
      // console.log(this.formList);

      // 去除优惠时段 hxj 2020-11-12
      // this.formList.find(x => x.fieldName === 'discountBeginTime|discountEndTime').initialValue = rangeTime;
      // this.timeLimited = this.formList.find(item => item.fieldName === 'isTimeLimited').initialValue;
    },
    isTimeLimited(props) {
      // console.log('props',props);
      this.timeLimited = props;
      // this.timeLimited = this.formList.find(item => item.fieldName ==='isTimeLimited').initialValue;
    },
    formChange(val) {
      this.saveData = val;
    },
    async saveAddform() {
      let formData = await this.$refs.formPanel.GET_FORM_DATA();
      if (formData[0]) return;
      this.saveData = formData[1];
      // console.log(this.saveData);
      if (this.saveData !== null) {
        if (this.saveData.discountBeginTime != null) {
          if (this.saveData.discountBeginTime == this.saveData.discountEndTime) {
            this.$notify.warning({ title: '提示信息', message: '优惠时段重叠，请重新输入！' });
            return;
          }
        }

        if (this.status == 'add') {
          await this.addDiscountmodes();
        }
        if (this.status == 'edit') {
          await this.updataDiscountmodes();
        }
        // } else {
        //   this.$notify.error({ title: '提示信息', message: '结束日期不能小于开始日期' });
        // }
      }
      // else {
      //   this.$notify.error({ title: '提示信息', message: '有内容未填写' });
      // }
    },
    async addDiscountmodes() {
      const res = await addDiscountmodes(this.saveData);
      // console.log("res",res)
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '新增成功！' });
        this.closeDialog();
      }
    },
    async updataDiscountmodes() {
      const res = await updataDiscountmodes(this.dataId, this.saveData);
      // console.log("res",res)
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '修改成功！' });
        this.closeDialog();
      }
    },
    closeDialog() {
      this.$emit('close');
    }
  }
};
</script>

<style lang="less" scoped></style>
